<?php
namespace User\Controller;

class PublicController extends \Common\Controller\BaseController{
	public $user;

	public function _initialize(){
		parent::_initialize();
		$this->user = D('Members');
	}

	public function login($username=null,$password=null){
		if (IS_POST) {
            if($username==null || $password==null){
            	$this->error('所有输入项都不能为空^_^');
            }

			//判断登入类型
			if (regex($username,'mobile')) {
				//邮箱登入
				$map['usertel'] = $username;
			}else{
				$map['username'] = $username;
			}
			$user = $this->user->where($map)->find();

			if (!empty($user)) {
	            if(md5($password) !== $user['userpass']){
	            	$this->error("用户密码错误！");
	            }else{
            		session('user',$user);
            		session('user_auth_sign',authcode("$user[userpass]\t$user[uid]",'ENCODE'));
            		$this->success("成功登入！",U('User/Index/index'));
	            }
			}else{
				$this->error("无此用户！");
			}
		}else{
			$this->display();
		}
	}

	//用户退出
	public function logout(){
		session('user',null);
		session('user_auth_sign',null);
		$this->success("用户成功退出",U('Home/Index/index'));
	}

	public function register(){
		if (IS_POST) {
			$username = I('username');
			$userpass = I('userpass','','md5');
			$usertel    = I('usertel');

			if (!I('readcheck')) {
				$this->error('请勾选注册协议！');
			}

			$data = array(
				'username'       => $username,
				'userpass'       => $userpass,
				'usertel'        => $usertel,
				'last_login_ip'  => get_client_ip(),
				'create_time'    => time(),
				'last_login_time' => time(),
			);
			$result = $this->user->add($data);
			if ($result) {
				$map['username'] = $username;
		        $strUser = $this->user->where($map)->find();
        		session('user',$user);
        		session('user_auth_sign',authcode("$strUser[userpass]\t$strUser[uid]",'ENCODE'));
				$this->success("注册成功！",U('Home/Index/index'));
			}
		}else{
			//是否邀请注册
			$fuserid = I('get.uid');    //邀请人UID

			$data = array(
				'fuserid'   => $fuserid,
			);
			$this->assign($data);
			$this->display();
		}
	}
	//注册检测
	public function regcheck(){
		$name = I('name');
		$value = I('param');

		$strUser = $this->user->field($name)->where("`".$name."`='".$value."'")->find();

		if (empty($strUser)) {
			$this->success("验证通过！");
		}else{
			$this->error("该帐号已注册！");
		}
	}
}